package com.blockmeta.bbs.immodule.corebean.Impl;

import android.content.Context;
import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.baselibrary.net.callback.BaseResponseCallBack;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseImResponse;
import com.blockmeta.bbs.businesslibrary.net.pojo.UserInfo;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.bean.databean.UserBean;
import com.blockmeta.bbs.immodule.corebean.IDomainCommonManger;
import com.blockmeta.bbs.immodule.corebean.IUserDomainService;
import com.blockmeta.bbs.immodule.dao.IMUserEntity;
import com.blockmeta.bbs.immodule.greendao.repository.IUserRepo;
import com.blockmeta.bbs.immodule.net.api.GetServiceUserListApi;
import com.blockmeta.bbs.immodule.net.api.GetUser;
import com.blockmeta.bbs.immodule.net.api.GetUserInfoApi;

import java.util.List;

/**
 * Created by author on 2019/3/19.
 * todo 后期改成依赖注入方式
 */

public class UserDomainService implements IUserDomainService {


    final Context mContext;
    IUserRepo userRepo;
    IDomainCommonManger domainCommonManger;

    public UserDomainService(Context context) {
        mContext = context;
        userRepo = IMRepoContext.getIMUserRepo(context);
        domainCommonManger = IMApplicationContext.getDomainCommonManger();
    }

    /**
     * 单个用户头像查询
     *
     * @param userID
     * @param needUpdate
     * @param callBack
     */

    @Override
    public void getUser(long userID, boolean needUpdate, final BaseResponseCallBack<String, IMUserEntity> callBack) {
        if(needUpdate){
            getUserFromNet(userID, callBack);
        }else {
            final IMUserEntity user = getUser(userID, Params.USER_PERSON);
            if (user != null) {
                if(callBack != null){
                    callBack.success(user);
                }
            } else {
                getUserFromNet(userID, callBack);
            }
        }
    }

    private void getUserFromNet(long userID, final BaseResponseCallBack<String, IMUserEntity> callBack) {
        RetrofitFactory.getRootRetrofit().create(GetUserInfoApi.class)
                .getUserInfo(String.valueOf(userID))
                .compose(RxUtil.<BaseImResponse<UserInfo>>rxSchedulerHelper())
                .compose(RxUtil.<UserInfo>commonResult())
                .subscribe(new CommonSubscriber<UserInfo>(mContext) {
                    @Override
                    public void onNext(UserInfo userBean) {
                        LogUtils.i("xiak", "单个数据请求结果！" + userBean.toString());
                        IMUserEntity IMUserEntity = new IMUserEntity();
//                            IMUserEntity.setRemarkName(userBean.getNick_name());
                        IMUserEntity.setUserId(userBean.getUserId());
                        IMUserEntity.setAvatarPath(userBean.getLogo());
                        IMUserEntity.setWhoId(AccountHelper.getUidInt());
                        IMUserEntity.setName(userBean.getUserName());
                        IMUserEntity.setType(Params.USER_PERSON);
                        IMUserEntity.setUserLevel(userBean.getGroupId());
                        IMUserEntity.setDate(String.valueOf(userBean.getRegdate()));
                        IMUserEntity.setSignature(userBean.getIndividualResume());
                        IMUserEntity user = addAndUpdateUserInfo(AccountHelper.getUidInt(), IMUserEntity);
                        if(callBack != null){
                            callBack.success(user);
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        callBack.fail(t.getMessage());
                        LogUtils.d("author" + "getuser error" + t.getMessage());
                    }
                });
    }

    private IMUserEntity addAndUpdateUserInfo(int uidInt, IMUserEntity imUserEntity) {
        return userRepo.addAndUpdateUserInfo(uidInt, imUserEntity);
    }

    /**
     * 获取服务号信息保存到数据库
     */
    @Override
    public void getCustomerServiceList() {
//        RetrofitFactory.getRetrofit().create(GetServiceUserListApi.class)
//                .getServiceUserListApi()
//                .compose(RxUtil.<List<UserBean>>commonResultByCode())
//                .compose(RxUtil.<List<UserBean>>rxSchedulerHelper())
//                .subscribe(new CommonSubscriber<List<UserBean>>(mContext) {
//                    @Override
//                    public void onNext(List<UserBean> list) {
//                        LogUtils.d("author" + "同步服务号信息" + list.size());
//                        IMApplicationContext.getUserDomainService().addCustomerServiceUsers(list);
//                    }
//                });
    }

    @Override
    public List<IMUserEntity> searchFriendPaged(String word, int pageSize, int page, String orderField, String orderType) {
        return userRepo.searchIMUserPaged(word, pageSize, page, orderField, orderType, Params.USER_PERSON);
    }

    @Override
    public List<IMUserEntity> searchCirclePaged(String word, int pageSize, int page, String orderField, String orderType) {
        return userRepo.searchIMUserPaged(word, pageSize, page, orderField, orderType, Params.USER_GROUP);
    }

    @Override
    public IMUserEntity getUser(long fromId, int type) {
        return domainCommonManger.getUser(fromId, type);
    }

    @Override
    public List<IMUserEntity> getBookListFriends(long uidInt) {
        return userRepo.getBookListFriends(uidInt);
    }


    @Override
    public boolean isFriend(long uidInt, long id) {
        IMUserEntity imUserEntity = userRepo.getUser(AccountHelper.getUidInt(), id, Params.USER_PERSON);
        return imUserEntity != null && imUserEntity.getIsFriend();
    }

    @Override
    public void changeUserRemarkName(String trim, long friendId) {
        IMUserEntity friend = getUser(friendId, Params.USER_PERSON);
        if (friend != null) {
            friend.setRemarkName(trim);
            userRepo.updateUser(friend);
        }

    }


    @Override
    public IMUserEntity addAndUpdateUser(long uidInt, IMUserEntity user) {
        return userRepo.addAndUpdateUser(uidInt, user);
    }


    @Override
    public void updateUserAvator(String mUserId, String avator) {
        //更新im数据库中个人信息图像
        IMUserEntity user = getUser(Long.parseLong(mUserId), Params.USER_PERSON);
        if (user != null && user.getAvatarPath() != null
                && !user.getAvatarPath().equals(avator)) {
            user.setAvatarPath(avator);
            userRepo.updateUser(user);
        }
    }

    @Override
    public boolean isFriend(long userId) {
        IMUserEntity user = getUser(userId, Params.USER_PERSON);
        return user != null && user.getIsFriend();
    }


    @Override
    public void addFriend(final long userId, final BaseResponseCallBack callBack) {
        getUser(userId, false, new BaseResponseCallBack<String, IMUserEntity>() {
            @Override
            public void fail(String msg) {
            }

            @Override
            public void success(IMUserEntity iMUserEntity) {
                LogUtils.d("author" + "addFriend" + userId);
                IMUserEntity mUser = getUser(userId, Params.USER_PERSON);
                mUser.setIsFriend(true);
                userRepo.updateUser(mUser);
                if(callBack != null){
                    callBack.success(iMUserEntity);
                }
            }
        });
    }

    @Override
    public void deleteFriend(long userId) {
        LogUtils.d("author" + "deleteFriend" + userId);
        IMUserEntity mUser = getUser(userId, Params.USER_PERSON);
        if (mUser != null) {
            mUser.setIsFriend(false);
            //将之前好友的备注名清楚
            mUser.setRemarkName("");
            userRepo.updateUser(mUser);
        }
    }


    @Override
    public void updateUserNameAndAvator(final long userId, final String userName, final String userAvator, final int userGroupId) {
        LogUtils.d("author" + "update local user info");
        getUser(userId, false, new BaseResponseCallBack<String, IMUserEntity>() {
            @Override
            public void fail(String msg) {
            }

            @Override
            public void success(IMUserEntity userEntity) {
                if (userEntity == null) {
                    return;
                }
                LogUtils.d("author" + "update local user info2");
                if (!TextUtils.isEmpty(userName)) {
                    if (!userEntity.getName().equals(userName)) {
                        userEntity.setName(userName);
                    }
                }
                if (!TextUtils.isEmpty(userAvator)) {
                    if (!userEntity.getAvatarPath().equals(userAvator)) {
                        userEntity.setAvatarPath(userAvator);
                    }
                }
                if (userGroupId != 0) {
                    if (userEntity.getUserLevel() != userGroupId) {
                        userEntity.setUserLevel(userGroupId);
                    }
                }
                userRepo.updateUser(userEntity);
            }
        });


    }

    @Override
    public void addCustomerServiceUsers(List<UserBean> list) {
        if (list == null) {
            return;
        }
        for (UserBean userBean : list) {
            IMUserEntity IMUserEntity = new IMUserEntity();
//            IMUserEntity.setRemarkName(userBean.getNick_name());
            IMUserEntity.setUserId(userBean.getId());
            IMUserEntity.setAvatarPath(userBean.getLogo());
            IMUserEntity.setWhoId(AccountHelper.getUidInt());
            IMUserEntity.setName(userBean.getName());
            IMUserEntity.setType(Params.USER_PERSON);
            IMUserEntity.setUserLevel(userBean.getGroupId());
            IMUserEntity.setDate(userBean.getDate());
            IMUserEntity.setCustomerService(true);
            addAndUpdateUser(AccountHelper.getUidInt(), IMUserEntity);
        }

    }


//    @Override
//    public void addUsers(List<UserBean> list) {
//        if(list == null){
//            return;
//        }
//        for(UserBean userBean : list){
//            IMUserEntity IMUserEntity = new IMUserEntity();
////            IMUserEntity.setRemarkName(userBean.getNick_name());
//            IMUserEntity.setUserId(userBean.getId());
//            IMUserEntity.setAvatarPath(userBean.getLogo());
//            IMUserEntity.setWhoId(AccountHelper.getUidInt());
//            IMUserEntity.setName(userBean.getName());
//            IMUserEntity.setType(Params.USER_PERSON);
//            IMUserEntity.setUserLevel(userBean.getGroupId());
//            IMUserEntity.setDate(userBean.getDate());
//            userRepo.addAndUpdateUser(AccountHelper.getUidInt(), IMUserEntity);
//        }
//
//    }

}
